Repository navigation
Keep the cause of a ToString override's error in str() - #175
Conversation
ClassBase.tp_str replaced the exception thrown by ToString() with its InnerException, to unwrap reflection wrappers. A Python override's error arrives as a PythonException, whose InnerException is the Python error's __cause__, so str() raised the cause instead of the error. A PythonException is now raised as it is; other exceptions are unwrapped as before. Closes #170 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approved, risk:low: a one-line guard in tp_str, easy to revert. All other exceptions are unwrapped exactly as before. Covered by tests and green CI, including the Lean regression and unit test runs, and tested end to end.
I checked it locally: tests/test_repr.py passes with the change. Without the ClassBase.cs change, test_str_python_tostring_raises fails with KeyError: 'inner', so the test reproduces #170. Exceptions.SetError restores a PythonException as is, so the original error and its __cause__ reach Python unchanged.
The same unwrap pattern elsewhere: Iterator.tp_iternext calls MoveNext() directly and has the same bug. A Python IEnumerator whose MoveNext raises ValueError(...) from KeyError(...) surfaces the KeyError; I reproduced this on this branch and opened #177 for it. It doesn't block this change. MethodBinder and the PropertyObject getter unwrap one level after a reflection Invoke, so a PythonException there is kept.
There was a problem hiding this comment.
Approved; no introduced defects found. The guard preserves the original Python error and its cause while leaving non-Python exception unwrapping unchanged.
Independent verification on Python 3.11 / .NET 10:
- Python suite: 488 passed, 23 skipped.
- Embedding tests: 1049 passed, 8 skipped, plus 1 passed for the isolated Python-path test.
- Managed Python runner: 2 passed.
- Against unchanged master, the new chained-error regression fails with
KeyError: 'inner'; it passes with this change. - End-to-end exception assertions passed and the algorithm completed. The process subsequently encountered a shutdown error; an unchanged-master control produced the same error, so it is not introduced here.
Separately, a directly thrown .NET ToString exception with an inner exception still loses its outer exception on both master and this head. Filed #178; it does not block this narrowly scoped fix.
After release, Lean needs its pinned pythonnet package references updated.
Closes #170
What changed and why
ClassBase.tp_strcatches whatToString()throws and used to raise itsInnerExceptionwhenever it had one, to strip reflection wrappers such as theTargetInvocationExceptionthrown when a Python subclass inherits a .NETToString. A PythonToStringoverride's error arrives as aPythonException, whoseInnerExceptionis the Python error's__cause__(PythonException.FromPyErr). So forraise ValueError("outer") from KeyError("inner"),str()raised theKeyError, andexcept ValueErrordidn't catch it.tp_strnow raises aPythonExceptionas it is, so the error keeps its type and its__cause__. Every other exception is unwrapped as before. That covers:ClrBubbledExceptionwrapping the original and still reaches Python as the original .NET exceptionToStringthat throwsToString, whose exception is wrapped in aTargetInvocationExceptionand still unwrappedtp_repris unchanged. It already falls back to the default repr whenToString()throws, and #170 is aboutstr().Tests
New tests in
tests/test_repr.py:test_str_python_tostring_raises: a__namespace__subclass ofSystem.ObjectwhoseToStringoverride raises:ValueError("outer") from KeyError("inner"):str()raises theValueError, and its__cause__is theKeyErrorValueError: raised with no causeInvalidOperationException: raised as that typeWithout the runtime change, the chained case fails with
KeyError: 'inner'.test_str_tostring_throws:str()of a .NET type whoseToStringthrows, called directly and through a__namespace__subclass that inherits it, raises theInvalidOperationException. It passes both before and after the change, and guards the unwrapping that is kept.The CI steps, run locally on Python 3.11 / .NET 10 after
pip install -v .:dotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 488 passed, 23 skippeddotnet test --runtime any-x64 src/python_tests_runner/: 2 passedAlso tested end to end in a Lean Python backtest whose algorithm calls
str()on the three kinds of override above and fails unless each result is right:KeyError: 'inner'.ValueError: outerwith aKeyErrorcause,ValueError: plainwith no cause, andInvalidOperationException: from .NET.The change is backwards compatible except for the fixed case:
str()raises the same exceptions as before for everything except aPythonExceptionthat has a cause.